import os
import google.generativeai as genai
import dotenv

# Load environment variables from .env file
dotenv.load_dotenv()

# Configure the API key for the Gemini model
api_key = os.environ.get("GEMINI_API_KEY")
if not api_key:
    raise ValueError(
        "API key not found! Ensure GEMINI_API_KEY is "
        "set in the environment variables."
    )

genai.configure(api_key=api_key)

# Initialize the Generative Model
model = genai.GenerativeModel("gemini-1.5-flash")


def generate_response(user_input):
    """
    This function interacts with the Gemini model
    to generate creative and intelligent responses.

    :param user_input: The user's input to the chatbot.
    :return: A response generated by the AI.
    """
    try:
        response = model.generate_content(user_input)
        return (
            response.text
            if response
            else "Sorry, I couldn't generate a response."
        )
    except Exception as e:
        return f"An error occurred: {e}"


def chatbot():
    """
    Main function to handle continuous interaction with the chatbot.
    It allows the user to ask anything from blog posts to code explanations.
    """
    print("🚀 Welcome to the most amazing AI Bot! 🌟")
    print(
        "💬 You can ask me anything from writing blog posts, "
        "to explaining code, to creative writing.\n"
    )
    print("✨ Just type 'exit' anytime to quit.\n")

    while True:
        # Get user input
        user_input = input("You: ")

        # Check for exit condition
        if user_input.lower() == "exit":
            print("👋 Goodbye! Thanks for chatting!")
            break

        # Generate and print AI response
        ai_response = generate_response(user_input)
        print(f"AI Bot: {ai_response}\n")


if __name__ == "__main__":
    # Run the chatbot
    chatbot()
